<?php

namespace app\common\model\xilujob;

use app\admin\model\User;
use app\common\library\Auth;
use think\Db;
use think\Exception;
use think\Log;
use think\Model;
use traits\model\SoftDelete;
use function fast\array_get;

class Resume extends Model
{

    use SoftDelete;


    // 表名
    protected $name = 'xilujob_resume';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        //'status_text',
        //'black_text'
    ];
    protected $moduleClasses;
    protected $moduleConfig = [];


    public function __construct($data = [])
    {
        parent::__construct($data);
        $schemas = ResumeSchema::get_schema();
        foreach ($schemas as $schema){
            $this->moduleConfig[$schema['modules']] = $schema['schema_name'];
        }
    }

    public function user() {
        return $this->belongsTo(User::class, 'user_id','id',[],'LEFT')->setEagerlyType(0);
    }
    /**
     * 个人信息
     */
    public function personal() {
        return $this->hasOne(ResumePersonalInfo::class,'resume_id','id',[],'LEFT')->setEagerlyType(0);
    }

    /**
     * 求职意向
     */
    public function jobIntention() {
        return $this->hasMany('ResumeJobIntention', 'resume_id', 'id');
    }

    /**
     * 教育经历
     */
    public function educations() {
        return $this->hasMany('ResumeEducation', 'resume_id', 'id')->order('start','desc');
    }
    /**
     * 工作经历
     */
    public function works() {
        return $this->hasMany('ResumeWork', 'resume_id', 'id')->order('start','desc');
    }

    /**
     * 技能
     */
    public function skills() {
        return $this->hasMany('ResumeSkill', 'resume_id', 'id');
    }

    /**
     * 个人总结
     */
    public function summary() {
        return $this->hasOne('ResumeSummary', 'resume_id', 'id', [], 'LEFT');
    }

    /**
     * 简历附件
     */
    public function resumeFiles(){
        return $this->hasMany('ResumeFile', 'resume_id', 'id');
    }

    /**
     * 个人标签
     */
    public function personalTags() {
        return $this->belongsToMany(ResumePersonalTag::class, ResumePersonalTagRelation::class, 'tag_id','resume_id');
    }

    /**
     * 获取个人简历信息
     * @param $resumeId
     * @param bool $with
     * @return Resume
     */
    public static function getResume($resumeId, $with=false) {
        $resume = self::get($resumeId);
        if($with) {
            $schemas = ResumeSchema::get_schema();
            foreach($schemas as $schema) {
                $relation = $schema['modules'];
                $resume->$relation;
            }
        }
        return $resume;
    }


    /**
     * @param $user_id
     * @param bool $with
     * @return null|static
     */
    public static function getUserResume($user_id, $with=false) {
        //获取用户的memberID
        $member = Member::where('user_id', $user_id)->order('id','desc')->find();
        $resumeId = static::where('user_id', $user_id)->where('member_id',$member->id)->order('id','desc')->value('id');
        if(!$resumeId) {
            //创建一份简历
            $resume = \app\common\library\xilujob\ResumeLibrary::createResume($user_id,$member);
            if(!$resume) {
                return null;
            }
            $resumeId = $resume->id;
        }
        $resume = static::getResume($resumeId, $with);

        return $resume;
    }

    /**
     * 企业搜索简历
     * @param $params
     * @param $companyId
     * @return mixed
     */
    public static function searchResume($params, $companyId=null) {
        $page = intval(array_get($params, 'page', 1));
        $page = $page < 1 ? 1 : $page;

        $pagesize = array_get($params, 'pagesize', 10);
        if($pagesize<1){
            $pagesize = 10;
        }

        $with = ['personal', 'personal_tags'];
        $where = [];

        if($q = array_get($params,'q')) {
            $ids = JobCategory::where('name_path','like',':q')->bind('q', "%$q%")->column('id') ? : [0];
            $where['fav_category_id'] = ['in', $ids];
            try {
                if (Db::name('xilujob_resume_search_keyword')->where('keyword', $q)->count() > 0) {
                    Db::name('xilujob_resume_search_keyword')->where('keyword', $q)->update([
                        'search_count' => Db::raw('search_count+1')
                    ]);
                } else {
                    Db::name('xilujob_resume_search_keyword')->insert(['keyword' => $q, 'search_count' => 1]);
                }
            }catch (\Exception $e) {

            }
        }
        if($cityId = array_get($params, 'city_id')) {
            $where['fav_city_id'] = $cityId;
        }
        if($districtId = array_get($params,'district_id')) {
            $where['fav_area_id'] = $districtId;
        }
        if($districtId = array_get($params,'town_id')) {
            $where['fav_town_id'] = $districtId;
        }

        if($salaryId = array_get($params, 'salary_id')) {
            $where['expect_salary_id'] = ['in',$salaryId];
        }

        if($categoryId = array_get($params,'category_id')) {
            $jobCategory = JobCategory::field('id,path')->find($categoryId);
            $jobCategoryIds = JobCategory::where('path','like',$jobCategory->path.'%')->column('id') ? : [0];
            $where['fav_category_id'] = ['in',$jobCategoryIds];
        }

        #先查出符合要求的resume_id;
        //$job_intention = ResumeJobIntention::where($where)->page($page,$pagesize)->group('resume_id')->select();
        //$job_intention = array_column($job_intention,null,'resume_id');
        //$resumes_ids = $job_intention ? array_keys($job_intention) :[0];
       // $where2 = [];
        //$where2[] = ['resume.id','in',$resumes_ids];
        $where2[] = ['status',1];
        $where2[] = ['black', 0];
        $where2[] = ['complete_percent','>',10];
        if($companyId) {
            $where2[] = ['resume.user_id','not in',function($query) use($companyId) {
                $query->name('xilujob_user_blacklist_company')->where('company_id',$companyId)->field('user_id');
            }];
        }
        if($age=(array_get($params, 'age'))) {
            $age = explode(',',$age);
            $ageMin = abs(array_get($age, '0'));
            $ageMax = abs(array_get($age, '1'));

            if($ageMin){
                $ageMaxWhere = (date('Y')-$ageMin).'-'.date('m-d');
                $where2[] = ['personal.birthdate','<',$ageMaxWhere];
            }

            if($ageMax){
                $ageMinWhere = (date('Y')-$ageMax).'-'.date('m-d');
                $where2[] = ['personal.birthdate','>',$ageMinWhere];
            }
        }
        if($gender = array_get($params, 'gender')) {
            $where2[] = ['personal.gender', $gender];
        }
        if($workExperienceId = array_get($params, 'work_experience_id')) {
            $where2[] = ['personal.work_experience_id','in', $workExperienceId];
        }
        if($educationLevelId = array_get($params, 'education_level_id')) {
            $where2[] = ['personal.education_level_id', $educationLevelId];
        }
        if( ($refreshDays=intval(array_get($params, 'refresh_days'))) > 0) {
            $where2[] = ['resume.updatetime','>',time() - $refreshDays*86400];
        }


        $whereParam = function ($query) use ($where2) {
            foreach ($where2 as $k => $v) {
                if (is_array($v)) {
                    call_user_func_array([$query, 'where'], $v);
                } else {
                    $query->where($v);
                }
            }
        };
        $paginator = static::alias('resume')
            ->whereExists(function ($query) use($where){
                $jobIntention = (new ResumeJobIntention())->getQuery()->getTable();
                $query->table($jobIntention)->where('resume.id=' . $jobIntention . '.resume_id')->where($where)->whereNull('deletetime');
                return $query;
            })
            ->field('id,user_id,top,updatetime')
            //->join(config('database.prefix').'xilujob_resume_job_intention jobIntention','jobIntention.resume_id=resume.id')
            ->with($with)
            ->where($whereParam);
        $paginator->order('top','desc')
            ->order('refresh_date','desc')
            ->order('complete_percent','desc')
            ->order('resume.updatetime','desc');
            //->group('jobIntention.resume_id');
        $paginator = $paginator->paginate([
            'query' => $params, 'list_rows'=>$pagesize, 'page'=>$page
        ])
            ->each(function ($row) use($where){
            $row->job_intention = ResumeJobIntention::where($where)->where('resume_id',$row->id)->find();
        });
        return $paginator;
    }


    /**
     * 人才推荐 for 企业
     * @param User $user 企业用户
     * @param CompanyProfile $company 企业信息
     * @param array $params
     * @return Object
     */
    public static function recommendResumes($company, $params, $fill=null) {
        $page = abs(intval(array_get($params,'page')));
        $page = $page > 0 ? $page : 1;
        $pagesize = abs(intval(array_get($params, 'pagesize', 10)));
        $pagesize = $pagesize>0 ? $pagesize : 10;

        $where_intention = [];
        if($cityId = array_get($params, 'city_id')) {
            $where_intention['fav_city_id'] = $cityId;
            //$query->where('jobIntention.fav_city_id', $cityId);
        }
        if($company) {
            // 查询在招职位的对应简历
            $targetJobCategoryIds = Job::where('publisher_id', $company->id)
                //->where('status','<>', Job::STATUS_DISABLED)
                ->distinct('job_category_id')
                ->column('job_category_id');
            if($targetJobCategoryIds) {
                //$query->where('jobIntention.fav_category_id','in', $targetJobCategoryIds);
                $where_intention['fav_category_id'] = ['in', $targetJobCategoryIds];
            }
            //排除黑名单
//            $query->where('resume.user_id','not in',function($query) use($company) {
//                $query->name('xilujob_user_blacklist_company')->where('company_id',$company->id)->field('user_id');
//            });
            $user_ids = Db::name("xilujob_user_blacklist_company")
                ->where('company_id',$company->id)->distinct('user_id')
                ->column('user_id');
            if($user_ids){
                $where_intention['user_id'] = ['not in',$user_ids];
            }
        }

        #先查出符合要求的resume_id;
        //$job_intention = ResumeJobIntention::where($where_intention)->page($page,$pagesize)->group('resume_id')->select();
       // $job_intention = array_column($job_intention,null,'resume_id');
       // $resumes_ids = $job_intention ? array_keys($job_intention) :[0];
        //构造查询条件
        //$where['resume.id'] = ['in',$resumes_ids];
        //halt($job_intention);
        if($company) {
            $resumes = self::alias('resume')
                ->whereExists(function ($query) use($where_intention){
                    $jobIntention = (new ResumeJobIntention())->getQuery()->getTable();
                    $query->table($jobIntention)->where('resume.id=' . $jobIntention . '.resume_id')->where($where_intention);
                    return $query;
                })
                ->where('status', 1)
                ->where('black', 0)
                ->where('complete_percent','>', 0)
                ->order('refresh_date','desc')
                ->order('resume.updatetime','desc')
                ->with(['personal', 'personal_tags'])
                //->where($where)
                ->paginate([
                    'list_rows' => $pagesize,
                    'page' => $page
                ])
                ->each(function ($row) use($where_intention){
                    $row->job_intention = ResumeJobIntention::where($where_intention)->where('resume_id',$row->id)->find();
                });
        }else {
            // 不使用$where ， 因未登录用户无搜索功能
            $resumes = self::alias('resume')
                ->whereExists(function ($query) use($where_intention){
                    $jobIntention = (new ResumeJobIntention())->getQuery()->getTable();
                    $query->table($jobIntention)->where('resume.id=' . $jobIntention . '.resume_id')->where($where_intention);
                    return $query;
                })
                ->where('status', 1)
                ->where('black', 0)
                ->where('complete_percent','>', 0)
                ->order('refresh_date','desc')
                ->order('resume.updatetime','desc')
                ->with(['personal', 'personal_tags'])
                //->where($where)
                ->paginate([
                    'list_rows' => $pagesize,
                    'page' => $page
                ])->each(function ($row) use($where_intention){
                    $row->job_intention = ResumeJobIntention::where($where_intention)->where('resume_id',$row->id)->find();
                });
        }
        return $resumes;
    }


    /**
     * 获取相似简历
     * @param $id
     * @param array $params page,pagesize
     * @param int $companyId 公司id
     * @return Resume|\think\Paginator|null
     */
    public static function getSimilarResumes($id, $params,$companyId=0) {
        $resume = self::getResume($id);
        if(!$resume) {
            return null;
        }
        $favCategoryId = $resume->job_intention->fav_category_id;
        $page = abs(array_get($params,'page',1));
        $page = $page==0?1:$page;
        $pagesize = abs(array_get($params,'pagesize',10));
        $resumes = self::with(['personal','job_intention'])
            ->where('status',1)
            ->where('black', 0)
            ->where('complete_percent','>',0)
            ->where('resume.id','<>',$resume->id)
            ->where('jobIntention.fav_category_id','=',$favCategoryId);
        $user = Auth::instance()->getUser();
        $xilujob = XilujobUser::get(['user_id'=>$user->id]);
        if($xilujob && in_array($xilujob->enterprise_group_id,[2,3])) {
            $where[] = ['resume.user_id','not in',function($query) use($companyId){
                $query->name('user_blacklist_company')->where('company_id',$companyId)->field('user_id');
            }];
        }

        $resumes = $resumes->order('top','desc')
            ->limit(($page-1)*$pagesize, $pagesize)
            ->paginate(['list_rows'=>$pagesize,'page'=>$page,'query'=>$params]);
        return $resumes;
    }
}
